
#include "components/postid.h"
#include <QtCore>
#include "tasksavethread.h"
#include "threadsaver.h"
#include "components/thread.h"
#include "components/post.h"
#include "components/attachment.h"
#include "taskrequest.h"
#include "taskattachmentrequest.h"
#include "log.h"

namespace Wishmaster
{
	TaskSaveThread::TaskSaveThread(const ThreadPtr& thread, Connector* connector, Taskhub* hub,
								   ThreadBuilderPtr builder, const QString& path, const QString& msg)
		: Task(msg),
		m_thread(thread),
		m_taskhub(hub),
		m_builder(builder),
		m_connector(connector), m_path(path)
	{
	}

	TaskSaveThread::~TaskSaveThread()
	{
	}

	void TaskSaveThread::start()
	{
		for(int postNumber = 0; postNumber < m_thread->getActualPostsCount(); postNumber++)
		{
			PostPtr post = m_thread->getPost(postNumber);
			for(int index = 0; index < post->attachmentCount(); index++)
			{
				if(post->attachment(index)->type().startsWith("image") &&
				   post->attachment(index)->data().isEmpty())
					m_attachs.insert(PostId(post->id(), index), post->attachment(index));
			}
		}
		m_done = 0;
		m_total = m_attachs.size() + 1;
		for(HashAttachment::iterator it = m_attachs.begin(); it != m_attachs.end(); ++it)
		{
			TaskAttachmentRequest* request = new TaskAttachmentRequest(it.key(), 0, it.value()->url(),
												   tr("Requesting picture for post: "), m_connector);
			connect(request, SIGNAL(result(TaskAttachmentRequest*,QByteArray,QString)),
					this, SLOT(requestDone(TaskAttachmentRequest*,QByteArray,QString)));
			TaskPtr task(request);
			m_taskhub->queueTask(task);
		}
		if(m_total == 1) // No attachments
		{
			doSaving();
		}
	}

	void TaskSaveThread::cancel()
	{
	}

	void TaskSaveThread::requestDone(TaskAttachmentRequest* task, const QByteArray& arr, const QString& contentType)
	{
		m_thread->lookupPost(task->postId())->attachment(task->attachmentIndex())->setData(arr);
		m_attachs.remove(task->postId());

		setPercentage((double) m_done / m_total * 100.);
		emit progress(id(), m_done, m_total);
		m_done++;

		if(m_attachs.isEmpty())
			doSaving();
	}

	void TaskSaveThread::doSaving()
	{
		ThreadSaver saver;
		saver.save(m_thread, m_path, m_builder);
		emit progress(id(), m_total, m_total);
		emit done(id());
	}
}

